package cn.yuanqiao.archive.shuzihua.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantMdataList;
import cn.yuanqiao.archive.appManager.mapper.ArchiveMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantMdataListMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.shuzihua.domain.YqCatalog;
import cn.yuanqiao.archive.shuzihua.domain.YqCatalogDis;
import cn.yuanqiao.archive.shuzihua.mapper.YqCatalogDisMapper;
import cn.yuanqiao.archive.shuzihua.mapper.YqCatalogMapper;
import cn.yuanqiao.archive.shuzihua.service.CatalogueImportService;
import cn.yuanqiao.archive.shuzihua.utils.CatalogueUploadDao;
import cn.yuanqiao.archive.shuzihua.utils.CatalogueUploadDataList;
import cn.yuanqiao.archive.wenjianzhengli.utils.UploadDAO;
import cn.yuanqiao.archive.wenjianzhengli.utils.UploadDataListener;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.file.FileTypeUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.feignService.ApiSystemService;
import cn.yuanqiao.feignService.RemoteSysDeptService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONObject;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 目录导入
 *
 * @ProjectName: cn.yuanqiao.archive.shuzihua.service.impl
 * @ClassName: CatalogueImportServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2024/1/16 10:48
 * @Version: 1.0
 **/
@Service
public class CatalogueImportServiceImpl implements CatalogueImportService {
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private ITenantSysDictTypeService sysDictTypeService;
    @Autowired
    private TenantMdataListMapper mdataListMapper;
    @Autowired
    private YqCatalogMapper yqCatalogMapper;
    @Autowired
    private YqCatalogDisMapper yqCatalogDisMapper;
    @Autowired
    private ApiSystemService userService;
    @Autowired
    private RemoteSysDeptService deptService;
    @Autowired
    private ArchiveMapper archiveMapper;

    @Override
    public UploadDAO getTitle(Long categoryId, Integer type, MultipartFile file) throws Exception {
        String extension = FileTypeUtils.getExtension(file);
        UploadDAO uploadDAO = new UploadDAO(); //解析入库在这里面完成
        if ("xls".equals(extension) || "xlsx".equals(extension)) {
            uploadDAO.setType(0); //只解析表头
            EasyExcel.read(file.getInputStream(), new UploadDataListener(uploadDAO)).sheet().doRead();
        } else {
            throw new ServiceException("文件格式错误！");
        }
        return uploadDAO;
    }

    @Override
    public int upload(JSONObject data, MultipartFile file) throws Exception {
        //{"categoryId":"123","type":"1","itemId":"-1","folderId":"-1",
        // "colNames":[{"xlsNum":"0","xlsName":"标题","name":"TITLE","showType":"1"},{"xlsNum":"1","xlsName":"保管期限","name":"BGQX","showType":"3"}]}

        if (!data.containsKey("categoryId") || StringUtils.isEmpty(data.getString("categoryId"))
                && !data.containsKey("type") || StringUtils.isEmpty(data.getString("type"))
                && !data.containsKey("colNames") || StringUtils.isEmpty(data.getString("colNames"))
                && !data.containsKey("state") || StringUtils.isEmpty(data.getString("state"))
                && !data.containsKey("jsType") || StringUtils.isEmpty(data.getString("jsType"))) {
            throw new ServiceException("参数错误！");
        }
        TenantCategory category = categoryMapper.selectTenantCategoryByID(data.getLong("categoryId"), new TenantCategory().getTableName());
        if (category.getType() == 3 && data.getInteger("type") == 1
                && (!data.containsKey("itemId") || StringUtils.isEmpty(data.getString("itemId")))) {
            data.put("itemId", null);

        }
        if ((category.getType() == 3 || category.getType() == 1) && data.getInteger("type") == 0
                && (!data.containsKey("folderId") || StringUtils.isEmpty(data.getString("folderId")))) {
            data.put("folderId", null);
        }
        CatalogueUploadDao uploadDAO = new CatalogueUploadDao(); //解析入库在这里面完成
        String extension = FileTypeUtils.getExtension(file);
        if ("xls".equals(extension) || "xlsx".equals(extension)) {
            long beginTime = System.currentTimeMillis();
            LoginUser user = SecurityUtils.getLoginUser();
            uploadDAO.setType(1); //解析入库
            uploadDAO.setLoginUser(user);
            uploadDAO.setCategory(category);  //门类
            uploadDAO.setSqlSessionTemplate(sqlSessionTemplate);  //数据连接
            uploadDAO.setSysDictTypeService(sysDictTypeService); // 字典
            uploadDAO.setData(data);
            uploadDAO.setCreateTime(DateUtils.getTime());
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setType(data.getInteger("type"));
            uploadDAO.setMdataList(mdataListMapper.selectNotEmptyDefaultByCategoryId(mdataList, data.getLong("categoryId"), new TenantCategory().getTableName()));

            uploadDAO.setUserService(userService);
            uploadDAO.setDeptService(deptService);
            uploadDAO.setArchiveMapper(archiveMapper);

            EasyExcel.read(file.getInputStream(), new CatalogueUploadDataList(uploadDAO)).sheet().doRead();
            long endTime = System.currentTimeMillis();
            uploadDAO.setTime(endTime - beginTime);
            addLog(uploadDAO,data.getInteger("type"));
        }
        return 1;
    }

    /**
     * 新增导入日志
     *
     * @param uploadDAO
     */
    @Transactional(rollbackFor = SQLException.class)
    public void addLog(CatalogueUploadDao uploadDAO,int type) {
        YqCatalog yqCatalog = new YqCatalog();
        Long id = SnowflakeIdGenerator.generateId();

        yqCatalog.setCategoryCode(String.valueOf(uploadDAO.getCategory().getId()));
        yqCatalog.setSuccessNum(String.valueOf(uploadDAO.getSuccessSun()));
        yqCatalog.setFailNum(String.valueOf(uploadDAO.getErrorSun()));

        if (uploadDAO.getErrorSun().equals(0)) {
            yqCatalog.setState("0");
            yqCatalog.setMsg("总计导入" + uploadDAO.getZongshu() + "条，其中成功"+uploadDAO.getSuccessSun()+"条，耗时:" + longTileString(uploadDAO.getTime()));
        } else {
            yqCatalog.setState("1");
            yqCatalog.setMsg("总计导入" + uploadDAO.getZongshu() + "条，其中成功"+uploadDAO.getSuccessSun()+"条，其中失败" + uploadDAO.getErrorSun() + "条，耗时:" + longTileString(uploadDAO.getTime()));

            List<Map<String, String>> failDataList = uploadDAO.getFailData();

            List<String> collect = failDataList.stream().iterator().next().keySet().stream().distinct().collect(Collectors.toList());
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setType(type);
            mdataList.setGroupId(uploadDAO.getCategory().getGroupId());
            List<TenantMdataList> titleList = mdataListMapper.selectByFieldName(collect, mdataList);
            List<YqCatalogDis> yqCatalogDis = new ArrayList<>();
            for (Map<String, String> fa : failDataList) {
                YqCatalogDis dis = new YqCatalogDis();
                Map<String, String> errMap = new HashMap<>();
                dis.setMsg(fa.get("SYS_VERIFY_MSG"));
                fa.remove("SYS_VERIFY_MSG");
                fa.forEach((key, value) -> {
                    String colName = titleList.stream().filter(f -> f.getFieldName().equals(key)).map(m -> m.getFieldCaption()).distinct().collect(Collectors.joining());
                    if (org.apache.commons.lang3.StringUtils.isBlank(colName) && !"SYS_VERIFY_MSG".equals(key)) {
                        //  colName = key;
                        if ("TYPE".equals(key)) {
                            colName = "门类";
                        }
                        if ("QZH".equals(key)) {
                            colName = "全宗号";
                        }
                    }
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(colName)){
                        errMap.put(colName, value);
                    }
                });

                dis.setFailData(errMap.toString());
                dis.setLogId(id);
                dis.setId(SnowflakeIdGenerator.generateId());
                yqCatalogDis.add(dis);
            }
            if (yqCatalogDis != null && yqCatalogDis.size() > 0) {
                yqCatalogDisMapper.insertYqCatalogDisList(yqCatalogDis, new YqCatalogDis().getTableName());
            }
        }
        yqCatalog.setId(String.valueOf(id));
        yqCatalog.setBatchNum(String.valueOf(SnowflakeIdGenerator.generateId()));
        yqCatalog.setCreateTime(new Date());
        yqCatalog.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
        yqCatalogMapper.insertYqCatalog(yqCatalog, yqCatalog.getTableName());
    }

    /**
     * 查询
     *
     * @param yqCatalog
     * @return
     */
    @Override
    public List<YqCatalog> logList(YqCatalog yqCatalog) {
      //  TenantCategory category = categoryMapper.selectTenantCategoryByID(Long.valueOf(yqCatalog.getCategoryCode()), new TenantCategory().getTableName());
        yqCatalog.setCategoryCode(yqCatalog.getCategoryCode());
        PageUtils.startPage();
        return yqCatalogMapper.selectYqCatalogList(yqCatalog, yqCatalog.getTableName());
    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public List<YqCatalogDis> logById(String id) {
        PageUtils.startPage();
        return yqCatalogDisMapper.selectYqCatalogDisByLogId(id, new YqCatalogDis().getTableName());
    }


    private String longTileString(long time) {
        if (time < 1000L) {
            return time + "毫秒";
        } else if (time <= 60000L) {
            return (time / 1000L) + "秒";
        } else {
            return (time / (60L * 1000L)) + "分钟";
        }
    }

}
